/************************************************************************************/
/*  Program name CAPAPIMP_PAY_PROGRAM.sql                                           */
/*  Creater:  WONG Wing Kin (PCCW - UniHub)                                         */
/*************   History   *************************                                */
/* 30 NOV, 2005   WONG Wing Kin         First created                               */
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;
ALTER TRIGGER AP_PAYMENT_PROGRAMS_CT1 DISABLE;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPAPIMP_PAY_PROGRAM';

	lv_Scc_Count	NUMBER			:=	0;
	lv_Err_Count	NUMBER			:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_AP_PAY_PROGRAMS;

	CURSOR Cur_G IS
	SELECT
		A.*,
		B.Program_ID_N
	FROM
		CAP_PAYMENT_PROGRAMS		A,
		CRST_AP_PAY_PROGRAMS_MAP	B
	WHERE	A.Program_ID	=	B.Program_ID;

	lv_Next_Seq_ID	NUMBER;

BEGIN

	--  RENAME
	UPDATE
		AP_PAYMENT_PROGRAMS
	SET
		Program_Name	=	CAPBRIMP_MAPPING.RenameStr(SUBSTR(Program_Name,1,4),Program_Name),
		Friendly_Name	=	CAPBRIMP_MAPPING.RenameStr(SUBSTR(Friendly_Name,1,4),Friendly_Name)
	WHERE	Program_ID	IN	(
							SELECT
								Program_ID
							FROM
								CRST_AP_PAY_PROGRAMS
							);

	FOR C1 IN Cur_F LOOP
		BEGIN
			SELECT	AP_PAYMENT_PROGRAMS_S.NextVal
			INTO	lv_Next_Seq_ID
			FROM	DUAL;

			INSERT INTO CRST_AP_PAY_PROGRAMS_MAP VALUES
			(
			C1.PROGRAM_ID,
			C1.FRIENDLY_NAME,
			lv_Next_Seq_ID,
			C1.FRIENDLY_NAME
			);

			INSERT INTO AP_PAYMENT_PROGRAMS
			VALUES
			(
			lv_Next_Seq_ID,
			C1.PROGRAM_NAME,
			C1.PROGRAM_TYPE,
			C1.FRIENDLY_NAME,
			C1.LAST_UPDATE_DATE,
			CAPBRIMP_COMMON.GetUser(C1.LAST_UPDATED_BY_NAME),		--LAST_UPDATED_BY,
			C1.CREATION_DATE,
			CAPBRIMP_COMMON.GetUser(C1.CREATED_BY_NAME),			--CREATED_BY,
			C1.LAST_UPDATE_LOGIN,
			C1.TRANSMISSIONS_ENABLED
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;

	BEGIN
		FOR C2 IN Cur_G LOOP
			INSERT INTO CAP_PAYMENT_PROGRAMS VALUES
			(
				C2.Program_ID_N,
				CAPBRIMP_MAPPING.GetOrgMapping(C2.S_ORG_ID),
				CAPBRIMP_MAPPING.GetBGMapping(C2.S_BUSINESS_GROUP_ID)
			);
		END LOOP;
	EXCEPTION
		WHEN OTHERS THEN
			DBMS_OUTPUT.Put_Line(SQLERRM);
			lv_Err_Count	:=	lv_Err_Count + 1;
	END;

	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);

	--COMMIT;
END;
/
ALTER TRIGGER AP_PAYMENT_PROGRAMS_CT1 ENABLE;